package cn.ytxy.ivos.application.service.impl;


import cn.ytxy.ivos.application.mapper.ApplicationMapper;
import cn.ytxy.ivos.application.pojo.dto.ApplicationQuery;
import cn.ytxy.ivos.application.pojo.dto.ApplicationSaveParam;
import cn.ytxy.ivos.application.pojo.entity.Application;
import cn.ytxy.ivos.application.pojo.vo.ApplicationVO;
import cn.ytxy.ivos.application.service.ApplicationService;
import cn.ytxy.ivos.audit.mapper.AuditMapper;
import cn.ytxy.ivos.audit.pojo.vo.AuditVO;
import cn.ytxy.ivos.audit.service.AuditService;
import cn.ytxy.ivos.base.enums.ApplicationStatusEnum;
import cn.ytxy.ivos.user.mapper.UserMapper;
import cn.ytxy.ivos.user.pojo.vo.UserVO;
import cn.ytxy.ivos.vehicle.mapper.VehicleMapper;
import cn.ytxy.ivos.vehicle.pojo.entity.Vehicle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @ClassName ApplicationServiceImpl
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/5/13 9:23
 * @Version 1.0
 */

@Transactional
@Slf4j
@Service
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private AuditService auditService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public void save(ApplicationSaveParam applicationSaveParam) {
        log.debug("保存申请单业务：applicationSaveParam={}", applicationSaveParam);
        Application application = new Application();
        BeanUtils.copyProperties(applicationSaveParam, application);
        //新增申请单，初始状态为已发起
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());

        //遇到的问题：新增申请单对应的审批单数据是，审批数据没有申请单的id
        //原因：id是一个比较特殊的属性，无法通过任何select条件获取
        //解决办法：给insert方法对应的sql上加useGeneratedKeys="true" keyProperty="id"
        //让jdbc为当前的application对象自动生成自增主键并把生成的主键赋值给当前application对象的id字段
        applicationMapper.insert(application);
        //还需要调用审批业务层，为当前申请单同步新增对应的审批单数据
        auditService.insertAudit(application);
    }

    @Override
    public List<ApplicationVO> selectApplication(ApplicationQuery applicationQuery) {
        log.debug("查询申请单业务applicationQuery={}", applicationQuery);
        List<ApplicationVO> list = applicationMapper.selectApplication(applicationQuery);
        //此处返回没有返回到审批人信息需要去查询,因此遍历每一个申请单，因此为每个遍历到的申请单添加审批人数据
        for (ApplicationVO applicationVO : list) {
            //处理当前的申请单VO，给他添加审批人数据
            assignAuditUserList(applicationVO);
        }
        return list;

    }

    /**
     * 本方法用于给当前传入的申请单vo的审批人数据赋值
     */
    private void assignAuditUserList(ApplicationVO applicationVO) {
        //准备空集合，分别用来保存申请单对应的审批人姓名和id集合
        ArrayList<String> auditUsernameList = new ArrayList<>();
        ArrayList<Long> auditUserIdList = new ArrayList<>();
        //2.根据传入的申请单的id查询对应的审批数据，注意：审批数据可能有多条
        List<AuditVO> auditVOList = auditService.selectAuditByApplicationId(applicationVO.getId());
        //3.依次遍历每一个审批单对象
        for (AuditVO auditVO : auditVOList) {
            //4.取出审批VO中的审批人id，装入上方的空集合中
            Long id = auditVO.getAuditUserId();
            auditUserIdList.add(id);
            //5.根据id查询审批人的姓名，装入上方的空集合中
            UserVO userVO = userMapper.selectById(id);
            auditUsernameList.add(userVO.getUsername());
        }
        //6.准备一个拼接工具，将所有审批人姓名连成一个字符串
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String string : auditUsernameList) {
            stringJoiner.add(string);
        }
        applicationVO.setAuditUserIdList(auditUserIdList);
        applicationVO.setAuditUsernameList(stringJoiner.toString());
    }


    @Override
    public void cancel(Long id) {
        log.debug("撤销申请单业务：id={}", id);
        Application application = new Application();
        application.setId(id);
        //设置当前申请单的状态为撤销
        application.setStatus(ApplicationStatusEnum.CANCEL.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        //还需要删除此申请单所对应的审批单
        auditMapper.deleteAuditByApplicationId(id);
    }

    @Override
    public void distribute(Long applicationId, Long vehicleId) {
        log.debug("分配车辆业务，applicationId={},vehicleId={}", applicationId, vehicleId);
        Application application = new Application();
        application.setId(applicationId);//设置要更新那个申请单
        application.setVehicleId(vehicleId);//设置给申请单分配哪辆车
        //更新申请单状态为已分配车辆
        application.setStatus(ApplicationStatusEnum.ALLOCATION.getCode());
        application.setUpdateTime(new Date());
        applicationMapper.update(application);

        //车辆也需要修改为占用
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);//设置更新那辆车
        vehicle.setStatus("2");//设置车辆状态为占用
        vehicle.setUpdateTime(new Date());//设置更新时间
        vehicleMapper.update(vehicle);//执行车辆表的更新操作，注意车辆mapper需要注入!
    }

    @Override
    public void back(Long applicationId, Long vehicleId) {
        log.debug("归还车辆，applicationId={},vehicleId={}", applicationId, vehicleId);
        Application application = new Application();
        application.setId(applicationId);
        /*方案一：车辆状态改为空闲，申请单状态改为工单结束，但申请单的车辆id任然保留*/
//        application.setVehicleId(vehicleId);//设置要归还那辆车
        /*方案二：茶凉状态改为空闲，申请单状态改为工单结束，但申请单的车辆id设置为null，将id留在日志中去保留*/
        application.setVehicleId(null);//设置要归还那辆车
        application.setStatus(ApplicationStatusEnum.END.getCode());
        application.setUpdateTime(new Date());
        /*方案一：可以使用之前的更新sql*/
//        applicationMapper.update(application);
        /*方案2：需要重写一个将车辆id置为null*/
        applicationMapper.back(application);

        //还车需要把车辆状态改为空闲
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.update(vehicle);
    }
}
